<template>
  <z-paging ref="pagingRef" :auto="false">
    <template #top>
      <view :style="{ height: getStatusBarHeight() + 'px' }"></view>
      <image
        src="/static/home/home_header_logo.png"
        mode="scaleToFill"
        class="w-70% h-56rpx ml-20rpx"
      />
    </template>
    1111
  </z-paging>
</template>
<script setup>
import { onMounted, reactive, ref, unref, nextTick, computed } from "vue";
import { onShow, onLoad, onHide } from "@dcloudio/uni-app";
import {
  GetReceiveListApi,
  GetAllGamesListApi,
  SaveCollect,
} from "@/api/modules/orders.js";
import dayjs from "dayjs";
import IndexList from "./components/indexList.vue";
import Pop from "./components/pop.vue";
import SortPopup from "./components/sort-popup.vue";
import { formateStr, replaceUrl, isDesktopSafari } from "@/utils/index.js";
import { getStatusBarHeight } from "@/utils/system.js";
import useStore from "@/stores";

const { globalStore, useOrderStore } = useStore();

const emit = defineEmits(["onKeyboardHeightChange"]);
const isShowRate = ref(false);
const dataList = ref([]);
const currentVal = ref();
const isShow = ref(false); //是否展示游戏和区服
const popRef = ref(); //是否展示筛选
const sortpopupRef = ref(); //是否展示综合排序
const actionRef = ref(); //是否展示游戏下拉框
const gamesParams = ref({});
const agentTypeList = ref([
  {
    name: "代练",
    id: 1,
  },
  {
    name: "陪玩",
    id: 2,
  },
  {
    name: "私人",
    id: 3,
  },
]);
const orderType = ref(1); //订单类型 1-代练 2-陪练 3-私人
const orderInfoList = ref([]);

const orderLevelList = ref([
  {
    name: "普通订单",
    orderLevel: 1,
  },
  {
    name: "优质订单",
    orderLevel: 2,
  },
  {
    name: "高级订单",
    orderLevel: 3,
  },
  {
    name: "综合排序",
    orderLevel: 4,
  },
  {
    name: "",
    orderLevel: 5,
    imgUrl: "../../static/receive/screen_logo.png",
  },
]);
const ImgList = ref([
  "https://autun.oss-cn-beijing.aliyuncs.com/prod/image/home/banner/20240622/18b944b0af424adab165787f3b3e335f.jpg",
  "https://autun.oss-cn-beijing.aliyuncs.com/prod/image/home/banner/20250430/c7a15fabbc784d2f96b766047a3805d4.png",
]); // 轮播图
// 点击轮播图
const ImgClick = (e) => {
  switch (e) {
    case 0:
      break;
    case 1:
      break;
    default:
      break;
  }
};
const openFilterList = () => {
  uni.navigateTo({
    url: "/pages_public/details/index",
  });
};
//搜索
const handleSearch = () => {
  //	清空他的主页跳转携带的值
  if (initParams.searchContent !== globalStore.receiveSearchVal) {
    globalStore.setReceiveSearchVal(initParams.searchContent);
  }

  dataList.value = [];
  //	获取列表
  scrollViewRef.value?.reloadData({
    ...initParams,
  });
};
//查看订单
const ViewDetails = (item) => {
  if (!item.isRead) {
    // #ifdef H5
    useOrderStore.addReadOrder(item.orderId); // 持久化存储
    // #endif

    item.isRead = true; // 更新当前视图
  }
  if (globalStore.token) {
    SaveCollect({
      type: 2,
      orderNo: item.orderNo,
    }).then(() => {});
  }
  uni.navigateTo({
    url: `/pages_receive/orders_list/index?status=${item.status}&orderId=${item.orderId}`,
  });
  onShowFlag.value = 0;
};
//打开游戏筛选框
const handleClick = () => {
  popRef.value.close();
  sortpopupRef.value.close();
  actionRef.value.toggle();
};
//游戏筛选提交
const handleGamesSubmit = (params) => {
  gamesParams.value = params;
  currentVal.value = gamesParams.value.current;
  //	获取列表
  initParams.gamesId = gamesParams.value.gamesId;
  initParams.gamesRegionId =
    gamesParams.value.gamesRegionId * 1 === 0
      ? ""
      : gamesParams.value.gamesRegionId;
  initParams.gamesRegionIdList = gamesParams.value.gamesRegionIdList;

  scrollViewRef.value?.reloadData({
    ...initParams,
  });
  popRef.value.resetInit();
};
//综合排序
const handleSort = (params) => {
  // sortParams.value = params
  orderLevelList.value[3].name = params.type === 1 ? "综合排序" : params.name;

  sortpopupRef.value.close();
  //	获取列表
  initParams.sort = params.type;
  // 为了点击筛选列表后再点价格排序 参数丢失
  const filterObj = filterParams.value ? filterParams.value : {};
  scrollViewRef.value?.reloadData({
    ...initParams,
    ...filterObj,
  });
};

const initParams = reactive({
  type: 1, //1 接单大厅 2 接手订单 3 发布订单
  status: 1, // 状态 1 全部 2代练中 3 待验收 4售后中 5 已完结
  isLogin: globalStore.token ? 1 : 0,
  orderType: orderType.value, //订单类型 1-代练 2-陪练 3-私人
  orderLevel: 1, //订单级别 1-普通 2-优质 3-高级
  searchContent: "",
  gamesId: gamesParams.value.gamesId, //游戏id
  gamesRegionId: gamesParams.value.gamesRegionId,
  isMerchant: globalStore.token
    ? globalStore.userInfo?.platform * 1 === 3
      ? globalStore.parentUserInfo.isMerchant
      : globalStore.userInfo.isMerchant
    : "",
});

const scrollViewRef = ref();

const getOrderInfo = async (data) => {
  // 使用Store中的方法合并已读状态
  // #ifdef H5
  dataList.value = useOrderStore.setIsRead(data);
  // #endif

  // #ifdef APP || MP-WEIXIN
  dataList.value = data;
  // #endif
};

// 订单级别 1-普通 2-优质 3-高级
const handleActiveOrderLevel = (item) => {
  if (item.orderLevel < 4) {
    initParams.orderLevel = item.orderLevel;
  }
  switch (item.orderLevel) {
    case 1:
    case 2:
    case 3:
      sortpopupRef.value.close();
      actionRef.value.close();
      popRef.value.close();
      dataList.value = [];
      const params = popRef.value.getSearchData();
      uni.$uv.debounce(
        () => {
          //	获取列表
          scrollViewRef.value?.reloadData({
            ...params,
          });
        },
        500,
        false
      );
      break;
    case 4:
      actionRef.value.close(); //游戏列表
      popRef.value.close(); // 高级筛选
      sortpopupRef.value.open(); //综合排序
      break;
    case 5:
      actionRef.value.close();
      sortpopupRef.value.close();

      popRef.value.open(gamesParams.value || "");
      break;
  }
};
const filterParams = ref();
//筛选完成后的内容
const submit = (data) => {
  let temp = uni.$uv.deepClone(data);
  for (let i in temp) {
    if (temp[i] === "默认") {
      delete temp[i];
    }
    if (typeof temp[i] === "string" || typeof temp[i] === "number") {
      if (temp[i] === 0) {
        delete temp[i];
      }
    }
  }
  filterParams.value = temp;
  scrollViewRef.value?.reloadData({
    ...initParams,
    ...temp,
  });
};
//订单类型 1-代练 2-陪练 3-私人
const handleChange = (e) => {
  //等于私人的时候去登录
  if (e === 2 && !globalStore.token) {
    uni
      .$showModal({
        title: "",
        content: "暂未登录，请先登录!",
        confirmVal: "确定",
        cancelVal: "取消",
      })
      .then(() => {
        uni.navigateTo({
          url: "/pages/login/index",
        });
        onShowFlag.value = 0;
      });
    return;
  }
  sortpopupRef.value.close();
  actionRef.value.close();
  popRef.value.close();
  initParams.orderLevel = 1;
  orderType.value = e;
  initParams.orderType = e;
  uni.$uv.debounce(
    () => {
      //	获取列表
      scrollViewRef.value?.reloadData({
        ...initParams,
      });
    },
    500,
    false
  );
};

//	更新筛选字体选中样式
const activefiltter = ref(false);

function updateActiveStatus(e) {
  activefiltter.value = e;
}

function navigateTo(url) {
  if (globalStore.token) {
    uni.navigateTo({
      url,
    });
    onShowFlag.value = 0;
  } else {
    uni
      .$showModal({
        title: "",
        content: "暂未登录，请先登录!",
        confirmVal: "确定",
        cancelVal: "取消",
      })
      .then(() => {
        uni.navigateTo({
          url: "/pages/login/index",
        });
        onShowFlag.value = 0;
      });
  }
}

function resetFiltrate() {
  popRef.value.reset();
}
const allGamesList = ref([]);
//获取所有游戏
const getAllGames = async () => {
  const { data } = await GetAllGamesListApi();
  data.gamesInfoList.unshift({
    name: "全部游戏",
    id: "",
  });
  allGamesList.value = data.gamesInfoList;
  // 初始化时处理单价最高选项
  const initGameItem = {
    name: "全部游戏",
    id: "",
    code: "",
  };
  handleRateOption(initGameItem);
};
// 通用的处理单价最高选项显示的函数
const handleRateOption = (item) => {
  // 判断是否显示单价最高选项
  // 当选择"全部游戏"或"王者荣耀"时显示单价最高
  isShowRate.value = item.code === "001" || item.name === "全部游戏";

  console.log(
    "当前选择游戏:",
    item.name,
    "是否显示单价最高:",
    isShowRate.value
  );

  if (isShowRate.value) {
    // 检查是否已经存在"单价最高"选项，避免重复添加
    const existingRateOption = agentTypeList.value.find(
      (option) => option.id === 4
    );
    if (!existingRateOption) {
      agentTypeList.value.push({
        name: "单价最高",
        id: 4,
      });
    }
  } else {
    // 移除"单价最高"选项
    const rateOptionIndex = agentTypeList.value.findIndex(
      (option) => option.id === 4
    );
    if (rateOptionIndex > -1) {
      agentTypeList.value.splice(rateOptionIndex, 1);
    }
  }
};

//
const handleTabsChange = (item) => {
  initParams.gamesId = item.id;
  // 使用通用函数处理单价最高选项
  handleRateOption(item);

  gamesParams.value = {
    gamesId: item.id,
    code: item.code,
  };
  initParams.gamesRegionId = "";
  initParams.gamesRegionIdList = [];
  scrollViewRef.value?.reloadData({
    ...initParams,
  });
};
//	防止接口多次调用
const onShowFlag = ref(0);
// onShowFlag.value === 0 && globalStore.tabbarIdx === 2

onMounted(() => {
  getAllGames();
  initParams.searchContent = globalStore.receiveSearchVal;
  scrollViewRef.value?.refreshData({
    ...initParams,
  });
});

// 	键盘高度变化事件
const KeyboardHeight = ref(true);
// #ifndef H5
uni.onKeyboardHeightChange((res) => {
  KeyboardHeight.value = res.height * 1 === 0;
  emit("onKeyboardHeightChange", KeyboardHeight.value);
});
// #endif
</script>

<style scoped lang="scss">
@import "@/styles/receive.scss";
</style>
